package cn.com.eado.preado.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import cn.com.eado.crm.app.utils.LogUtil
import cn.com.eado.crm.m.repository.LoginRepository
import cn.com.eado.crm.model.AbsentLiveData
import cn.com.eado.crm.model.Resource

/**
 *
 */
class LoginViewModel : ViewModel() {
    private val repository by lazy { LoginRepository() }

    private val _login = MediatorLiveData<Boolean>()  //可观察的
    private val login: LiveData<Boolean> = _login
    //http请求参数
    var name = ""
    var pwd = ""
    var mac = ""

    //指定请求返回的类型为:String（本app的所有请求基本使用此方式）
    val loginResult: LiveData<Resource<String>> = Transformations.switchMap(login){ login ->
        if (login){
            LogUtil.e("LoginViewModel", "loginResult: name = $name, pwd = $pwd, mac = $mac")
            repository.login(name, pwd, mac)
        }else{
            AbsentLiveData.create()  //null
        }
    }

    fun setLogin(b: Boolean){
        _login.value = b  //赋值时，会触发loginResult的执行。true:则执行repository.login(name, pwd, mac)
    }

}